/*
 * AutosVentana.java
 *
 */

package ar.com.educacionit.vehiculos.ventanas;

import ar.com.educacionit.vehiculos.entidades.Auto;
import ar.com.educacionit.vehiculos.util.AdministradorDeConexiones;
//import com.mysql.jdbc.Connection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import java.sql.Connection;

/**
 *
 * @author  Sebastian S. Sanga <SebastianSanga@gmail.com>
 */
public class AutosVentana extends javax.swing.JInternalFrame {
    
    // Atributo para manejar si hay una ventana abierta de este tipo
    public static boolean abierta = false;
    DefaultListModel modeloAutos = new DefaultListModel();
    
    public AutosVentana() {
        
        // Llama al constructor de la superclase y establece las caracteristicas de ventana
        super("Administracion de Autos",
                true, //resizable
                true, //closable
                true, //maximizable
                true);//iconifiable
        
        // Establece en true el atributo abierto representando que hay una ventana de este tipo abierta
        abierta = true;
        
        // Invoca al metodo initComponents()
        initComponents();

        //carga de marcas de auto
        cargaMarcas();
        cargasColores();
        cargaModelos();
        listAutos.setModel(modeloAutos);

        llenarListaDeAuto();
        
    }

    public void llenarListaDeAuto(){
//        // Variables
//        Connection c = null;
//
//        try {
//            // Obtiene la conexion
//            c = AdministradorDeConexiones.getConnection();
//
//            // Obtiene todos los autos
//            List autos = Auto.obtenerTodos(c);
//
//            // Llena la lista de autos
//            listAutos.setListData(new Vector(autos));
//
//        } catch(Exception e){
//            JOptionPane.showMessageDialog(this, "Disculpe, no se ha podido obtener los autos", "Error", JOptionPane.ERROR_MESSAGE);
//            e.printStackTrace();
//        } finally{
//            if(c != null){
//                try{c.close();} catch(Exception e){}
//            }
//        }
            //otra forma de llenar lista de autos
             Connection conn = null;
         try{
             conn = AdministradorDeConexiones.getConnection();
             ArrayList<Auto> autos = Auto.obtenerTodos(conn);

             for(Auto o: autos){
             modeloAutos.addElement(o);
             }

         }catch(Exception e){
         JOptionPane.showMessageDialog(this, "Disculpe, no se ha podido obtener los autos", "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally{
            if(conn != null){
                try{
                    conn.close();
                } catch(Exception e){}
             }
        }
    }
    public void limpiarFormulario(){
        txtAltura.setText("");
        txtAncho.setText("");
        txtLargo.setText("");
        txtPrecio.setText("");
        txtEquipamiento.setText("");
        cmbColor.setSelectedIndex(0);
        cmbModelo.setSelectedIndex(0);
        cmbMarca.setSelectedIndex(0);
    }
    
    public void cargaModelos(){
        cmbModelo.addItem("Seleccione...");

        for(int i=1976;i<2011;i++){
            cmbModelo.addItem(String.valueOf(i));
        }
    }

    public void cargaMarcas(){      
    try{
        cmbMarca.addItem("Seleccione...");
        InputStreamReader isr = new InputStreamReader( AutosVentana.class.getResourceAsStream("/ar/com/educacionit/vehiculos/recursos/marcas.txt") );
        BufferedReader readerMejorado = new BufferedReader( isr );
       while(readerMejorado.ready()){
            String info = readerMejorado.readLine();
            cmbMarca.addItem(info);
        }
    } catch(Exception e){

           // Muestra el mensaje de error
           JOptionPane.showMessageDialog(this,
                                            "Error al cargar las marcas!\n" + "ERROR: " + e.getMessage(),
                                            "Error",
                                            JOptionPane.ERROR_MESSAGE);
       }


    }
   public void cargasColores(){

         try{
        cmbColor.addItem("Seleccione...");
        InputStreamReader isr = new InputStreamReader( AutosVentana.class.getResourceAsStream("/ar/com/educacionit/vehiculos/recursos/colores.txt") );
        BufferedReader readerMejorado = new BufferedReader( isr );
       while(readerMejorado.ready()){
            String info = readerMejorado.readLine();
            cmbColor.addItem(info);
        }
    } catch(Exception e){

           // Muestra el mensaje de error
           JOptionPane.showMessageDialog(this,
                                            "Error al cargar los colores!\n" + "ERROR: " + e.getMessage(),
                                            "Error",
                                            JOptionPane.ERROR_MESSAGE);
       }
    }

    public boolean validarFormulario(){
        
        // Valida que la altura no este vacio
        if(txtAltura.getText().equals("")){
            JOptionPane.showMessageDialog(this, "La altura no puede estar vacio!", "Guardar", JOptionPane.WARNING_MESSAGE);
            txtAltura.requestFocus();
            return false;
        }
        
        // Valida que la altura sea un numero entero
        try {
            Integer.parseInt(txtAltura.getText());
        } catch(Exception NumberFormatException){
            JOptionPane.showMessageDialog(this, "La altura debe ser un numero entero!", "Guardar", JOptionPane.WARNING_MESSAGE);
            txtAltura.requestFocus();
            return false;
        }
        
        // Valida que el ancho no este vacio
        if(txtAncho.getText().equals("")){
            JOptionPane.showMessageDialog(this, "El ancho no puede estar vacio!", "Guardar", JOptionPane.WARNING_MESSAGE);
            txtAncho.requestFocus();
            return false;
        }
        
        // Valida que el ancho sea un numero entero
        try {
            Integer.parseInt(txtAncho.getText());
        } catch(Exception NumberFormatException){
            JOptionPane.showMessageDialog(this, "El ancho debe ser un numero entero!", "Guardar", JOptionPane.WARNING_MESSAGE);
            txtAncho.requestFocus();
            return false;
        }
        
        // Valida que el largo no este vacio
        if(txtLargo.getText().equals("")){
            JOptionPane.showMessageDialog(this, "El largo no puede estar vacio!", "Guardar", JOptionPane.WARNING_MESSAGE);
            txtLargo.requestFocus();
            return false;
        }
        
        // Valida que el largo sea un numero entero
        try {
            Integer.parseInt(txtLargo.getText());
        } catch(Exception NumberFormatException){
            JOptionPane.showMessageDialog(this, "El largo debe ser un numero entero!", "Guardar", JOptionPane.WARNING_MESSAGE);
            txtLargo.requestFocus();
            return false;
        }
        
        // Valida que el precio no este vacio
        if(txtPrecio.getText().equals("")){
            JOptionPane.showMessageDialog(this, "El precio no puede estar vacio!", "Guardar", JOptionPane.WARNING_MESSAGE);
            txtPrecio.requestFocus();
            return false;
        }
        
        // Valida que el precio sea un numero que puede tener decimales
        try {
            Double.parseDouble(txtPrecio.getText());
        } catch(Exception NumberFormatException){
            JOptionPane.showMessageDialog(this, "El precio debe ser un numero!", "Guardar", JOptionPane.WARNING_MESSAGE);
            txtPrecio.requestFocus();
            return false;
        }        
        
        // Valida que el equipamiento no este vacio
        if(txtEquipamiento.getText().equals("")){
            JOptionPane.showMessageDialog(this, "El equipamiento no puede estar vacio!", "Guardar", JOptionPane.WARNING_MESSAGE);
            txtEquipamiento.requestFocus();
            return false;
        }
        //valida que se seleccione una opcion en los combos
        if(cmbColor.getSelectedIndex()== 0){
            JOptionPane.showMessageDialog(this, "Seleccione un Color!", "Guardar", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        if(cmbMarca.getSelectedIndex()==0){
            JOptionPane.showMessageDialog(this, "Seleccione una Marca!", "Guardar", JOptionPane.WARNING_MESSAGE);
            return false;
        }

        if(cmbModelo.getSelectedIndex()==0){
            JOptionPane.showMessageDialog(this, "Seleccione un Modelo!", "Guardar", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        
        return true;
    }
    
    public void agregarAutoALista(Auto a){
        
        // Construye el auto a partir de los datos de la ventana
        
        a.setAltura( Integer.parseInt(txtAltura.getText()) );
        a.setAncho( Integer.parseInt(txtAncho.getText()) );
        a.setLargo( Integer.parseInt(txtLargo.getText()) );
        a.setPrecio(Double.parseDouble( txtPrecio.getText()));
        a.setEquipamiento( txtEquipamiento.getText() );
        a.setColor( (String)cmbColor.getSelectedItem() );
        a.setMarca( (String)cmbMarca.getSelectedItem() );
        a.setModelo( (String)cmbModelo.getSelectedItem() );
        
        
        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        cmbModelo = new javax.swing.JComboBox();
        cmbColor = new javax.swing.JComboBox();
        cmbMarca = new javax.swing.JComboBox();
        txtPrecio = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        txtAltura = new javax.swing.JTextField();
        txtAncho = new javax.swing.JTextField();
        txtLargo = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        btnNuevo = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listAutos = new javax.swing.JList();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtEquipamiento = new javax.swing.JTextArea();
        btnCerrar = new javax.swing.JButton();

        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosed(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jLabel3.setText("Color");

        jLabel2.setText("Modelo");

        jLabel1.setText("Marca");

        cmbColor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbColorActionPerformed(evt);
            }
        });

        cmbMarca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbMarcaActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Dimensiones"));

        jLabel6.setText("Altura");

        jLabel7.setText("Ancho");

        jLabel8.setText("Largo");

        jLabel9.setText("cm");

        jLabel10.setText("cm");

        jLabel11.setText("cm");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel6)
                    .add(jLabel7)
                    .add(jLabel8))
                .add(13, 13, 13)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, txtLargo)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, txtAncho)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, txtAltura, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE))
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jPanel1Layout.createSequentialGroup()
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(jLabel9))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(jLabel10)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel11)))
                .addContainerGap(39, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(jLabel9)
                    .add(txtAltura, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel7)
                    .add(jLabel10)
                    .add(txtAncho, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel8)
                    .add(jLabel11)
                    .add(txtLargo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnGuardar.setText("Guardar");
        btnGuardar.setEnabled(false);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnEliminar.setText("Eliminar");
        btnEliminar.setEnabled(false);
        btnEliminar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnEliminarMouseClicked(evt);
            }
        });
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Listado de Autos"));

        listAutos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listAutosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listAutos);

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Caracteristicas / Equipamiento"));

        txtEquipamiento.setColumns(20);
        txtEquipamiento.setRows(5);
        jScrollPane2.setViewportView(txtEquipamiento);

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                .add(20, 20, 20)
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
                .addContainerGap())
        );

        btnCerrar.setText("Cerrar");
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .add(btnNuevo)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnGuardar)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnEliminar)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 187, Short.MAX_VALUE)
                        .add(btnCerrar))
                    .add(layout.createSequentialGroup()
                        .add(10, 10, 10)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
                            .add(layout.createSequentialGroup()
                                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 52, Short.MAX_VALUE)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                        .add(jLabel1)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(cmbMarca, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 124, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(jLabel2)
                                            .add(jLabel3))
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 22, Short.MAX_VALUE)
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                            .add(org.jdesktop.layout.GroupLayout.TRAILING, cmbColor, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .add(org.jdesktop.layout.GroupLayout.TRAILING, cmbModelo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 124, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                            .add(txtPrecio, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
                            .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .add(21, 21, 21))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(20, 20, 20)
                        .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(14, 14, 14)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(cmbMarca, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel1))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(cmbModelo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel2))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(cmbColor, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel3))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(txtPrecio, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnGuardar)
                    .add(btnEliminar)
                    .add(btnCerrar)
                    .add(btnNuevo))
                .add(32, 32, 32))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        
        // Valida el formulario
        boolean validacionOk = validarFormulario();
        boolean esNuevo = true;
        // Si el formulario es valido, informa
        if(validacionOk){

            // Instancia un auto
                Auto a = new Auto();
                Connection conn = null;

            try {
                conn = AdministradorDeConexiones.getConnection();

                // Si hay un item seleccionado lo obtiene
                if (listAutos.getSelectedIndex() != -1) {
                    a = (Auto) listAutos.getSelectedValue();
                    esNuevo = false;
                }
                agregarAutoALista(a);
                if (esNuevo) {
                    modeloAutos.addElement(a);
                    a.insertar(conn);
                } else {
                    a.actualizar(conn);
                }
                // Limpia el formulario
                limpiarFormulario();

                } catch (Exception e) {
                // Informa que la operacion no pudo ser realizada
                JOptionPane.showMessageDialog(this,
                                        "La operacion no pudo ser realizada: " + e.getMessage(),
                                        "Operacion",
                                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }finally{
                try{conn.close();}
                catch(Exception e){}
            }
                
                //  Desactiva boton 'guardar'
                btnGuardar.setEnabled(false);
                //  Desactiva boton 'eliminar'
                btnEliminar.setEnabled(false);
                // Activa boton 'nuevo'
                btnNuevo.setEnabled(true);
                // Establece el foco en el boton 'nuevo'
                btnNuevo.requestFocus();
                // No deja ningun item seleccionado en la lista
                listAutos.clearSelection();

                JOptionPane.showMessageDialog(this, "El auto ha sido guardado!", "Guardar", JOptionPane.INFORMATION_MESSAGE);
        }
        
    }//GEN-LAST:event_btnGuardarActionPerformed
    
    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        
        // Limpia las cajas de texto
        limpiarFormulario();
        
        // Deshabilita boton nuevo
        btnNuevo.setEnabled(false);
        
        // Habilita boton guardar
        btnGuardar.setEnabled(true);

         btnEliminar.setEnabled(false);
        
        // Ubica el curso en la primer caja de texto
        txtAltura.requestFocus();
        
    }//GEN-LAST:event_btnNuevoActionPerformed
    
    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCerrarActionPerformed
    
    private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed
        
        // Cuando cierra la ventana, establece 'abierto' en falso
        abierta = false;
        
    }//GEN-LAST:event_formInternalFrameClosed

    private void cmbMarcaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbMarcaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbMarcaActionPerformed

    private void listAutosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listAutosMouseClicked

          // Activa el boton 'eliminar'
        btnEliminar.setEnabled(true);

        // Activa el boton 'guardar'
        btnGuardar.setEnabled(true);

        btnNuevo.setEnabled(true);

        // Obtiene el item seleccionado
        Auto a = (Auto) listAutos.getSelectedValue();

        // Completa las cajas de texto segun el elemento
        txtAltura.setText( String.valueOf(a.getAltura()) );
        txtAncho.setText( String.valueOf(a.getAncho()) );
        txtLargo.setText( String.valueOf(a.getLargo()) );
        txtPrecio.setText( String.valueOf(a.getPrecio()) );
        txtEquipamiento.setText( a.getEquipamiento() );

        // Completa los combos segun corresponda
        cmbColor.setSelectedItem( a.getColor() );
        cmbMarca.setSelectedItem(a.getMarca() );
        cmbModelo.setSelectedItem( a.getModelo() );


    }//GEN-LAST:event_listAutosMouseClicked

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed

        
        // Si hay un elemento seleccionado, lo elimina
        if(listAutos.getSelectedIndex()!=-1){

            // Consulta si desea eliminar el item
            int rta = JOptionPane.showConfirmDialog(this,
                                        "Desea eliminar el auto " + listAutos.getSelectedValue() + " ?",
                                        "Eliminar",
                                        JOptionPane.YES_NO_OPTION);

            // Si no desea borrarlo, entonces no lo borra
            if(rta == JOptionPane.NO_OPTION)
                return;

          Auto a = (Auto) listAutos.getSelectedValue();

          Connection conn = null;

            try {
                conn = AdministradorDeConexiones.getConnection();
                a.eliminar(conn);

            } catch (Exception e) {
                // Informa que la operacion no pudo ser realizada
                JOptionPane.showMessageDialog(this,
                                        "La operacion no pudo ser realizada: " + e.getMessage(),
                                        "Operacion",
                                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }finally{
                try{conn.close();}
                catch(Exception e){}
            }

            // Elimina el auto
            modeloAutos.remove( listAutos.getSelectedIndex() );

            // Deshabilita el boton 'eliminar'
            btnEliminar.setEnabled(false);

            // Deshabilita el boton 'guardar'
            btnGuardar.setEnabled(false);

            // Limpia el formulario
            limpiarFormulario();

            // Informa que el auto ha sido eliminado
            JOptionPane.showMessageDialog(this, "El auto ha sido eliminado!", "Eliminar", JOptionPane.INFORMATION_MESSAGE);
        }

    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnEliminarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEliminarMouseClicked


    }//GEN-LAST:event_btnEliminarMouseClicked

    private void cmbColorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbColorActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbColorActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JComboBox cmbColor;
    private javax.swing.JComboBox cmbMarca;
    private javax.swing.JComboBox cmbModelo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JList listAutos;
    private javax.swing.JTextField txtAltura;
    private javax.swing.JTextField txtAncho;
    private javax.swing.JTextArea txtEquipamiento;
    private javax.swing.JTextField txtLargo;
    private javax.swing.JTextField txtPrecio;
    // End of variables declaration//GEN-END:variables
    
}
